package demo.hdz.testui;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.database.Cursor;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


/**
 * @author hdz
 * @date 2018/07/04
 */
public class MainActivity extends AppCompatActivity {

    private ServiceConnection mServiceConn = null;
    private ShowHideActivityService mShowHideActivityService = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(!hasShortcut(getApplicationContext())) {
            addShortcut(getApplicationContext(), R.drawable.ui_72px);
        } else {
            Toast.makeText(MainActivity.this, "有快捷方式", Toast.LENGTH_SHORT).show();
        }

        ServiceConnectionInit();

        Button btnRadioButton = (Button) findViewById(R.id.btnRadioButton);
        btnRadioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, RadioButtonActivity.class);
                startActivity(intent);
            }
        });

        Button btnToggleButton = (Button) findViewById(R.id.btnToggleButton);
        btnToggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ToggleButtonActivity.class);
                startActivity(intent);
            }
        });

        Button btnAnimation = (Button) findViewById(R.id.btnAnimation);
        btnAnimation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AnimationActivity.class);
                startActivity(intent);
            }
        });

        Button btnJump = (Button) findViewById(R.id.btnJump);
        btnJump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, JumpActivity.class);
                intent.putExtra("name", "YYYYYYYYYYYYYYY");
                intent.putExtra("age", 25);
                startActivityForResult(intent, Constant.JUMP_REQUEST_CODE);
            }
        });

        Button btnShowTransparentActivity = (Button) findViewById(R.id.btnShowTransparentActivity);
        btnShowTransparentActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, TransparentActivity.class);
                startActivity(intent);
            }
        });

        Button btnActivityRightInLeftOut = (Button) findViewById(R.id.btnActivityRightInLeftOut);
        btnActivityRightInLeftOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, JumpAnimActivity.class);
                intent.putExtra("Style", "LeftInRightOut");
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left);
            }
        });

        Button btnUiAdapt = (Button) findViewById(R.id.btnUiAdapt);
        btnUiAdapt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, UiAdaptActivity.class);
                startActivity(intent);
            }
        });

        Button btnImageTextView = (Button) findViewById(R.id.btnImageTextView);
        btnImageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ImageTextActivity.class);
                startActivity(intent);
            }
        });

        TextView tvAndroidVer = (TextView) findViewById(R.id.tvAndroidVer);
        tvAndroidVer.setText("Android "+Build.VERSION.RELEASE+" "+Build.VERSION.SDK_INT);

        DisplayMetrics appDisplayMetrics = getApplication().getResources().getDisplayMetrics();
        Log.d(Constant.TAG, ""+appDisplayMetrics.widthPixels);


        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;
        String wh = width+"x"+height;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            DisplayMetrics metric = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getRealMetrics(metric);
            wh += "("+metric.widthPixels+"x"+metric.heightPixels+")";
        }
        TextView tvResolution = (TextView) findViewById(R.id.tvResolution);
        tvResolution.setText("分辨率："+wh);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断requestCode和resultCode的值便可以确定是哪个Activity回传回来的数据
        if (requestCode == Constant.JUMP_REQUEST_CODE) {
            if (resultCode == Constant.JUMP_RESULT_CODE) {
                //获取回传回来的数据放
                String name = data.getStringExtra("name");
                int age = data.getIntExtra("age", -1);
                Toast.makeText(this, "name: "+name+"\nage:  "+age, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
    }

    @Override
    protected void onDestroy() {
        mShowHideActivityService = null;
        unbindService(mServiceConn);
        super.onDestroy();
    }

    private void ServiceConnectionInit() {
        mServiceConn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                ShowHideActivityService.LocalBinder binder = (ShowHideActivityService.LocalBinder) service;
                mShowHideActivityService = binder.getService();
                mShowHideActivityService.setMainActivity(MainActivity.this);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                mShowHideActivityService = null;
            }
        };

        Intent intent = new Intent(this, ShowHideActivityService.class);
        bindService(intent, mServiceConn, Service.BIND_AUTO_CREATE);
    }



    /* *
    * 创建快捷方式参考：
    * https://blog.csdn.net/rentee/article/details/77005547
    * https://blog.csdn.net/chenliguan/article/details/77171376
    * https://www.cnblogs.com/jesonjason/p/5698013.html
    * https://blog.csdn.net/lanfei1027/article/details/48297409
    * https://blog.csdn.net/rentee/article/details/77005547
    * */
    private void addShortcut(Context context, int appIcon) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ShortcutManager scm = (ShortcutManager) getSystemService(SHORTCUT_SERVICE);

            // 获取当前应用名称
            String title = "App";
            try {
                final PackageManager pm = context.getPackageManager();
                title = pm.getApplicationLabel(pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)).toString();
            } catch (Exception e) {
                e.printStackTrace();
            }

            Intent launcherIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
            ShortcutInfo si = new ShortcutInfo.Builder(this, "dataroam")
                    .setIcon(Icon.createWithResource(this, appIcon))
                    .setShortLabel(title)
                    .setIntent(launcherIntent)
                    .setActivity(new ComponentName("demo.hdz.testui", "demo.hdz.testui.MainActivity"))
                    .build();
            assert scm != null;
            scm.requestPinShortcut(si, null);
        } else {
            addShortcut1(context, appIcon);
        }
    }
    private void addShortcut1(Context context, int appIcon) {
        Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");

        // 获取当前应用名称
        String title = "App";
        try {
            final PackageManager pm = context.getPackageManager();
            title = pm.getApplicationLabel(pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 快捷方式名称
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
        // 不允许重复创建（不一定有效）
        shortcutIntent.putExtra("duplicate", false);

        // 快捷方式的图标
        Parcelable iconResource = Intent.ShortcutIconResource.fromContext(context, appIcon);
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);

        // 设置意图和快捷方式关联程序，在卸载应用的时候同时删除桌面快捷方式
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        //上面的一句与下面的三句等效
        //Intent intent = new Intent(Intent.ACTION_MAIN);
        //intent.addCategory(Intent.CATEGORY_LAUNCHER);
        //intent.setClass(context, MainActivity.class);
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);

        context.sendBroadcast(shortcutIntent);
    }

    public static boolean hasShortcut(Context context) {
        boolean result = false;
        String title = null;
        try {
            final PackageManager pm = context.getPackageManager();
            title = pm.getApplicationLabel(pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        final String uriStr;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
            uriStr = "content://com.android.launcher.settings/favorites?notify=true";
        } else if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            uriStr = "content://com.android.launcher2.settings/favorites?notify=true";
        } else {
            uriStr = "content://com.android.launcher3.settings/favorites?notify=true";
        }
        final Uri CONTENT_URI = Uri.parse(uriStr);
        final Cursor c = context.getContentResolver().query(CONTENT_URI, null, "title=?", new String[]{title}, null);
        if (c != null && c.getCount() > 0) {
            result = true;
            c.close();
        }
        return result;
    }
}
